//引入模块
const express = require("express");
const pool = require("../util/pool.js");
const query = require("../util/query.js");
//创建路由器对象
let router = express.Router();
//挂载路由
//===============================================
//1.购物车列表 GET /list
//参数:无(获取当前用户的所有记录)
router.get("/list", async(req, res) => {
  //获取数据:无  
  //是否已登录
  let user = req.session.user;
  if (!user) {
    res.send({ code: 2, msg: "未登录" });
    return;
  }
  
  try {
    //获取当前用户的购物车
    let sql = `select * from v_user_cart where user_id = ${user.id} `;
    let result = await query(sql);
    if (result.length == 0) throw "当前用户没有购物车！"; 
    
    let data = result;
    res.send({ code: 1, msg: `购物车查询成功`, data });
  } catch (error) {
    res.send({ code: -1, msg: `购物车查询失败, 错误信息: ${error}` }); //throw err;
  }  
});


//2.添加购物车 POST /add
// 参数名	       参数说明
// goods_id	商品编号
// price  商品单价
// count 商品数量
router.post("/add", async(req, res) => {
  //是否已登录
  let user = req.session.user;
  if (!user) {
    res.send({ code: 2, msg: "未登录" });
    return;
  }
  
  try {
    //获取数据,验证数据 POST请求 从body中获取数据
    let goods_id = req.body.goods_id;
    if (!goods_id) throw "商品编号不能为空";
    let price = req.body.price;
    if (undefined==price) throw "商品单价不能为空";
    let count = req.body.count;
    if (undefined==count) throw "商品数量不能为空";

    //判断用户的购物车中是否已有该商品
    let sql = `SELECT id FROM user_cart WHERE user_id=${user.id} AND goods_id=${goods_id}`;
    // console.log(sql);
    let result = await query(sql);
    //执行SQL语句 
    if (result.length > 0) {
      //用户购物车已经有该商品，则加count
      sql = `UPDATE user_cart SET count=count+${count} WHERE user_id=${user.id} AND goods_id=${goods_id}`;
    } else {
      sql = `INSERT INTO user_cart(id,user_id,goods_id,price,count,is_checked) VALUES(NULL, ${user.id}, ${goods_id}, ${price},${count},true)`;
    }
    // console.log(sql);
    await query(sql);
    //响应返回
    res.send({ code: 1, msg: `添加成功 goods_id=${goods_id}` });
  } catch (error) {
    res.send({code: -1,msg: `添加失败, 错误信息: ${error}`}); 
  }   
}); 


//===============================================
//3.删除购物车 GET /delete  
// 参数名	       参数说明
// ids	多个编号(流水号)，用","分割"
router.get("/delete", async (req, res) => {
  //是否已登录
  let user = req.session.user;
  if (!user) {
    res.send({ code: 2, msg: "未登录" });
    return;
  }  

  try {
    //获取数据,验证数据
    let ids = req.query.ids;
    if (!ids) {      
      throw "编号（流水号)不能为空";
    }
    console.log("rewrerwere")
    //执行SQL语句    
    let sql = `DELETE FROM user_cart WHERE id in ( ${ids} )`;
    console.log(sql);
    await query(sql);//应该进一步判断影响的记录行数，> 0 则成功
    //响应返回
    res.send({ code: 1, msg: `删除成功 ：ids=${ids}` });
  } catch (error) {    
    res.send({code: -1,msg: `删除失败, 错误信息: ${error}`}); 
  }   
});

//===============================================
//4.购物车项修改购买数量 GET /updatecount
// 参数名	       参数说明
// id	编号(流水号)
// count 商品数量
router.get("/updatecount", async(req, res) => {
  //是否已登录
  let user = req.session.user;
  if (!user) {
    res.send({ code: 2, msg: "未登录" });
    return;
  }
  try {
    //获取数据,验证数据
    let id = req.query.id;
    if (!id) throw "编号（流水号)不能为空";
    let count = req.query.count;
    if (undefined==count) throw "商品数量不能为空";
    //执行SQL语句    
    let sql = `UPDATE user_cart SET count = ${count} WHERE id = ${id} `;
    console.log(sql);
    await query(sql);//应该进一步判断影响的记录行数，> 0 则成功
    //响应返回
    res.send({ code: 1, msg: `更新成功 ：id=${id}` });
  } catch (error) {
    res.send({code: -1,msg: `更新失败, 错误信息: ${error}`}); 
  }   
}); 

//===============================================
//5.购物车项修改是否勾选 GET /updatechecked
// 参数名	       参数说明
// id	编号(流水号)
// is_checked 是否选中
router.get("/updatechecked", async(req, res) => {
  //是否已登录
  let user = req.session.user;
  if (!user) {
    res.send({ code: 2, msg: "未登录" });
    return;
  }
  try {
    //获取数据,验证数据
    let id = req.query.id;
    if (!id) throw "编号（流水号)不能为空";
    let is_checked = req.query.is_checked; //类型是整数1/0
    console.log(is_checked)    
    //执行SQL语句    
    let sql = `UPDATE user_cart SET is_checked = ${is_checked} WHERE id = ${id} `;
    console.log(sql);
    await query(sql);//应该进一步判断影响的记录行数，> 0 则成功
    //响应返回
    res.send({ code: 1, msg: `更新成功 ：id=${id}` });
  } catch (error) {
    res.send({code: -1,msg: `更新失败, 错误信息: ${error}`}); 
  }   
});

//===============================================
//6.购物车列表（勾选商品） GET /listchecked
//参数:无(获取当前用户的所有记录)
router.get("/listchecked", async(req, res) => {
  //获取数据:无  
  //是否已登录
  let user = req.session.user;
  if (!user) {
    res.send({ code: 2, msg: "未登录" });
    return;
  }
  
  try {
    //获取当前用户的购物车
    let sql = `select * from v_user_cart where is_checked = 1 AND user_id = ${user.id} `;
    let result = await query(sql);
    console.log(sql);
    if (result.length == 0) throw "当前用户没有购物车！"; 
    
    let data = result;
    res.send({ code: 1, msg: `购物车查询成功`, data });
  } catch (error) {
    res.send({ code: -1, msg: `购物车查询失败, 错误信息: ${error}` }); //throw err;
  }  
});

//===============================================
module.exports = router;
